package com.hs.android.fortress.intro;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.hs.android.fortress.GameApplication;
import com.hs.android.fortress.R;
import com.hs.android.fortress.net.AsyncNetworking;
import com.hs.android.fortress.net.FormPostCommand;
import com.hs.android.fortress.net.ParamsMaker;
import com.hs.android.fortress.net.PositionService;

public class MenuActivity extends Activity implements onMenuBtnClickListener{
	
	private static final String TAG = MenuActivity.class.getSimpleName();

	public static final String MENU_TYPE = "menu";
	public static final int MENU_PLAY = 1;
	public static final int MENU_RECORD = 2;
	public static final int MENU_SETTING = 3;
	
	private FragmentManager fm;
	
	private MainMenuFragment mMainMenuFragment;
	private PlayMenuFragment mPlayMenuFragment;
	private RecordMenuFragement mRecordMenuFragement;
	private SettingMenuFragment mSettingMenuFragment;
	
	private String mUserId;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);
		
		mUserId = ((GameApplication)getApplication()).getUserId();
		
		fm = getFragmentManager();
		
		if(mMainMenuFragment == null){
			mMainMenuFragment = new MainMenuFragment();
			FragmentTransaction ft = fm.beginTransaction();
			ft.replace(R.id.menu_container, mMainMenuFragment).commit();
		}
		
		mMainMenuFragment.setMenuBtnListener(this);
		
		if(mPlayMenuFragment == null){
			mPlayMenuFragment = new PlayMenuFragment();
		}
		
		if(mRecordMenuFragement == null){
			mRecordMenuFragement = new RecordMenuFragement();
		}
		
		if(mSettingMenuFragment == null){
			mSettingMenuFragment = new SettingMenuFragment();
		}
	}
	
	@Override
	public void onClick(View v){
		FragmentTransaction ft = fm.beginTransaction();
		
		switch(v.getId()){
		case R.id.btn_play:
			ft.replace(R.id.menu_container, mPlayMenuFragment);
			break;
		case R.id.btn_setting:
			ft.replace(R.id.menu_container, mSettingMenuFragment);
			break;
		case R.id.btn_record:
			ft.replace(R.id.menu_container, mRecordMenuFragement);
			break;
		}
		
		ft.addToBackStack(null);
		ft.commit();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Intent i = new Intent(this,PositionService.class);
		startService(i);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopService(new Intent(this,PositionService.class));
		logout();
	}
	
	private void logout(){
		AsyncNetworking.newInstance(null, new FormPostCommand("/member/logout", ParamsMaker.makeIdParam(mUserId)), null).execute();
	}
}
